package models;

import play.*;
import play.db.jpa.*;

import javax.persistence.*;

import java.util.*;

/**
 * TopicRating.java Purpose: Model
 * 
 * @version 1.0 4/25/2011
 * @author Ahmed Mahmoud
 */

@Entity
public class TopicRating extends Model {

	@ManyToOne(cascade=CascadeType.PERSIST)
	public Topic topic;
	@ManyToOne(cascade=CascadeType.PERSIST)
	public User user;

	public int rating;

	/**
	 * 
	 * @param topic
	 *            the topic which was rated.
	 * @param user
	 *            the user who rated the topic.
	 * @param rating
	 *            the rating which was chosen by the user for this topic
	 */
	public TopicRating(Topic topic, User user, int rating) {
		this.topic = topic;
		this.user = user;
		this.topic.usersRatings.add(this);
		this.user.topicsRatings.add(this);
		this.topic.save();
		this.user.save();
		this.rating = rating;
	}

	/**
	 * it takes rating as parameter and then update the rating for this record.
	 * 
	 * @param rating
	 *            the rating which the user has chosen for certain topic.
	 * @param newTopicRating
	 *            the whole rating for the topic.
	 * @return TopicRating, the TopicRating object that was modified.
	 */
	public TopicRating updateRating(int rating, double newTopicRating) {
		topic.updateRating(newTopicRating); // the whole value
		this.rating = rating;
		this.save();
		return this;
	}
	
	/**
	 * @author Ahmed Mahmoud
	 * @return
	 * 
	 */
	public boolean cascadeDelete(){
		topic.usersRatings.remove(this);
		topic.save();
		user.topicsRatings.remove(this);
		user.save();
		this.delete();
		return true;
	}

}
